$(function () {
    // 常量设置区域
    var FIELD_TYPE = {
        "XPATH": 1,
        "JSONPATH": 2,
        "CONST": 3,
        "XML": 4
    }

    var PAGE_TYPE = {
        "HTML": 1,
        "JSON": 2,
        "XML": 3
    }

    // 传入变量
    var pageType = 1;

    // 变量定义区
    var currentTr
        ,allFieldConfigs = {}
        ,currentFieldConfig
        ,fieldConfigObj = {
            id: ""
        }
        ,idOrder = 0;

    var iconSuc = "ace-icon fa fa-check green bigger-110", iconMeta = "green ace-icon fa fa-info-circle",
        iconWarn = "ace-icon fa fa-info-circle orange";

    var trHlClass = "hl-tr"
        , fieldsTableId = "fields-table";

    var descriptionSelector = '//meta[@name="description"]',
        keywordsSelector = '//meta[@name="keywords"]'

    var targetSiteHomeUrl = '';

    function getTargetSiteHomeUrl() {
        return targetSiteHomeUrl;
    }

    // 初始化
    init();

    /**
     * 页面初始化
     */
    function init() {
        $("#ts-copyRow").on("click", function () {
            copyRow()
        });

        $("#ts-delAllRows").on("click", function () {
            delAllRows()
        });

        $(".ts-addRow").on("click", function () {
            addNewRow()
        });

        $(".ts-add-field-one").on("click", function () {
            e($(this))
        });

        $(".ts-add-field-all").on("click", function () {
            $("a.ts-add-field-one").each(function (t, i) {
                e($(this))
            })
        })

        $(".ts-chooseFieldType").on("click", function () {
            chooseFieldType($(this))
        })

        $(".input-field").on("focus change keyup keydown", $("#" + fieldsTableId), function () {
            isConfiger || !$(this).attr("readonly") ? (isConfiger && saveModalDataAllLocal(),
                dealField(this),
                h()) : showMsgErr("该字段值在页面不可见，暂不支持修改，如有需求，可定义新的字段。")
        })
        
        $(".input-field").on("blur", function () {
            dealFieldBlur(this)
        })
    }
    
    function h() {
        initDataDealValue(),
            initDefaultValue(),
            initFileDown(),
            initReplaces(),
            initDataDeals(),
            initRegex(),
            initSelector()
            initHtmlTags(currFieldConfig.htmlEles)
    }

    function initDataDealValue() {
        checkRadio("delAllImg", currFieldConfig.delAllImg),
            initCheckBoxItemByName(currFieldConfig.delImg, "delImgItem"),
            checkRadio("dela", currFieldConfig.dela),
            initCheckBoxItemByName(currFieldConfig.delAs, "delAsItem"),
            dealCheckBox("pType", currFieldConfig.pType),
            $("#preTxt").val(currFieldConfig.preTxt),
            $("#tailTxt").val(currFieldConfig.tailTxt),
            checkRadio("randType", currFieldConfig.randType);
        var e = getRadioCheckObjy("randType");
        e && changeRandTypeShow(e.attr("data-show")),
            $("#minRd").val(currFieldConfig.minRd),
            $("#maxRd").val(currFieldConfig.maxRd),
            $("#minRdtStr").val(currFieldConfig.minRdtStr),
            $("#maxRdtStr").val(currFieldConfig.maxRdtStr),
            $("#timeFmt").val(currFieldConfig.timeFmt),
            $("#txtRd").val(currFieldConfig.txtRd),
            $("#lenType").val(currFieldConfig.lenType),
            $("#lenLimit").val(currFieldConfig.lenLimit),
            checkRadio("filterType", 0 == currFieldConfig.filterType ? 1 : currFieldConfig.filterType),
            $("#noInclude").val(currFieldConfig.noInclude),
            $("#mustInclude").val(currFieldConfig.mustInclude)
    }

    function changeRandTypeShow(e) {
        showChangeByClass(e, "ts-random-int-div"),
            showChangeByClass(e, "ts-random-time-div"),
            showChangeByClass(e, "ts-random-str-div")
    }

    function showChangeByClass(e, t) {
        e == t ? $("." + t).css("display", "block") : $("." + t).css("display", "none")
    }

    function getRadioCheckObjy(e, t) {
        return t ? $("input[type='radio'][name='" + e + "']:checked", t) : $("input[type='radio'][name='" + e + "']:checked")
    }

    function checkRadio(e, t) {
        $("input[type='radio'][name='" + e + "'][value='" + t + "']").prop("checked", !0)
    }

    function initCheckBoxItemByName(e, t) {
        if (e) {
            dealCheckBox(t, !1);
            for (var i = e.split(","), n = 0, a = i.length; n < a; n++)
                setCheckBoxByName(t, i[n])
        } else
            dealCheckBox(t, !1)
    }

    function initSelector() {
        $("#ts-selectors").text(currFieldConfig.selectors),
            setFieldPathValue(currFieldConfig.selectors),
            $("#ts-fieldValue").html(""),
            $("#ts-fieldValue").html(genCurrFieldValueArr().join("\n"))
    }

    function genCurrFieldValueArr() {
        return genExtractValueArr(extractElementsCh(currFieldConfig.selectors), currFieldConfig.useHtml, currFieldConfig.useLink, currFieldConfig.valueType, currFieldConfig.attrName)
    }

    function genExtractValueArr(e, t, i, n, a) {
        var o = genExtractValueArrOri(e, t, i, n, a);
        return i && (o = genLinkForUseLink(o)),
            o
    }

    function genLinkForUseLink(e) {
        var t = [];
        if (!e || 0 == e.length)
            return t;
        for (var i = 0, n = e.length; i < n; i++) {
            var a = genLinkHrefShowValueByValue(e[i]);
            t.push(a)
        }
        return t
    }

    function genLinkHrefShowValueByValue(e) {
        return e ? (e.startsWith("/") && (e = getTargetSiteHomeUrl() + e),
        '<a href="' + e + '" target="_blank">' + e + "</a>") : ""
    }

    function extractElementsCh(e) {
        return runIfrFun("extractElements", e)
    }

    function dealFieldBlur(e) {
        $tr = e.parentNode.parentNode;
        var t = $(e).val();
        setTitle(t),
            currFieldConfig.name = t,
            saveCurrFieldConfig()
    }

    function e(e) {
        var t = e.attr("useHtml")
            , i = !(!t || "1" != t);
        addNewRowCommon(e.attr("fieldValue"), i)
    }

    function addNewRowCommon(e, t) {
        for (var i in allFieldConfigs)
            if (allFieldConfigs[i].name == e)
                return showMsgErr("字段名已存在，不能再添加同名字段！"),
                    !1;
        var n = {};
        (n = jsonClone(fieldConfigObj)).name = e,
        t && (n.useHtml = !0,
            n.valueType = "html");
        var a = "";
        "description" == e ? (a = descriptionSelector,
            n.selectors = descriptionSelector,
            n.isMeta = !0,
            n.valueType = "attr",
            n.attrName = "content") : "keywords" == e && (a = keywordsSelector,
            n.isMeta = !0,
            n.selectors = keywordsSelector,
            n.valueType = "attr",
            n.attrName = "content");
        var o = addInitRow(n);
        $currTr = o,
            upSetConfigMap(o),
            currFieldConfig = n,
            setFieldPathValue(a),
            saveCurrFieldConfig(),
            initFieldConfigShow(currFieldConfig),
            setFieldName(currFieldConfig.name, o),
            focusInput(o),
            hlCurrTr(o),
            clearIframe()
    }

    function resetFieldIcon(e) {
        var t = iconSuc
            , i = getRowFieldId(e)
            , n = allFieldConfigs[i];
        if (!n)
            return showMsgErr("获取不到配置字段！"),
                !1;
        var a = $("div.field-status>i", e)
            , o = "";
        n.selectors || (t = iconWarn,
            o = "未配置xpath规则或随机值"),
        n.isMeta && (n.selectors.startsWith("/html/head") || n.selectors.startsWith("//meta")) && (t = iconMeta,
            o = "该字段页面数据不可见，但服务器可以处理。"),
        "random" == n.valueType && (t = iconSuc,
            o = "随机值"),
            a.attr("class", t),
            a.attr("data-rel", "tooltip"),
            a.attr("data-original-title", o)
    }

    function addInitRow(e) {
        var t = addRow();
        setFieldName(e.name, t);
        var i = getRowFieldId(t)
            , n = getRowFieldId(t);
        return e.id = n,
            allFieldConfigs[i] = e,
            resetFieldIcon(t),
            t
    }

    function chooseFieldType(e) {
        $(".hl-tr #fieldType .choosedFieldType")[0].innerText = e[0].innerText;
        $(".hl-tr #fieldType .choosedFieldType").attr("fieldvalue",e.attr("fieldvalue"))
    }

    function addNewRow() {
        var e = addRow();
        currentTr = e,
            upSetConfigMap(e),
            (currFieldConfig = getCurrFieldConfig()).name = getFieldName(e),
            currFieldConfig.selectors = "",
            setFieldPathValue(""),
            saveCurrFieldConfig(),
            initFieldConfigShow(currFieldConfig),
            setFieldName(currFieldConfig.name, e),
            focusInput(e),
            hlCurrTr(e),
            clearIframe()
    }

    function getCurrFieldConfig() {
        if (currentTr)
            return getExistFieldConfig(currentTr);
        alert("请选择要复制的字段，鼠标点一下字段名输入框即可")
    }

    function getExistFieldConfig(e) {
        if (e) {
            var t = getRowFieldId(e);
            return allFieldConfigs[t]
        }
        alert("获取指定行配置，行对象为空")
    }

    function initFieldConfigShow(e) {
        e || (e = fieldConfigObj),
            setTitle(e.name),
            dealCheckBox("required", e.required),
            dealCheckBox("delaTxt", e.delaTxt > 0),
            dealCheckBox("dela", e.dela > 0),
            dealCheckBox("dela-keeptxt", 2 == e.dela),
            dealCheckBox("useHtml", e.useHtml),
            dealCheckBox("cleanHtml", e.cleanHtml),
            dealCheckBox("keepAlt", e.keepAlt),
            dealCheckBox("useLink", e.useLink),
            dealCheckBox("useImg", e.useImg),
            dealCheckBox("mutiValue", e.mutiValue),
            dealCheckBox("groupSelect", e.groupSelect),
            $("#selectors").val(e.selectors),
            setFieldPathValue(e.selectors),
            setPageSelector(e.pageSelector),
            initMutiPagrValue(),
            initChangeValueType(e.valueType, e.attrName),
            initHtmlTags(e.htmlEles)
    }

    function initMutiPagrValue() {
        if (!currFieldConfig)
            return !1;
        dealCheckBox("mutiPage", currFieldConfig.mutiPage),
            showMutiPage(1 == currFieldConfig.mutiPage),
            $("#pageSelector").val(currFieldConfig.pageSelector),
            checkRadio("pageSave", currFieldConfig.pageSave),
            $("#pageConcat").val(currFieldConfig.pageConcat),
            $("#maxPage").val(currFieldConfig.maxPage),
            $("#urlContain").val(currFieldConfig.urlContain)
    }

    function showMutiPage(e) {
        e ? $(".ts-setMutiPager-div").removeClass("hide") : $(".ts-setMutiPager-div").addClass("hide")
    }

    function setPageSelector(e) {
        $("#pageSelector").val(e)
    }

    function setTitle(e) {
        e || (e = ""),
            $(".ts-show-fieldName").html("<Strong>" + e + "</Strong>"),
            runIfrFun("changeFieldName", e)
    }

    function delAllRows() {
        showMsgConfirm("确定要删除全部字段吗?", function (e) {
            e && ($("#" + fieldsTableId + ">tbody tr:not(:first)").each(function () {
                $(this).remove()
            }),
                allFieldConfigs = {},
                currentTr = "",
                currFieldConfig = null,
                setTitle(""),
                removeFieldValues(),
                setEmptyConfig(),
                clearIframe())
        })
    }

    function setEmptyConfig(e) {
        initFieldConfigShow(JSON.parse(JSON.stringify(fieldConfigObj)))
    }

    function removeFieldValues() {
        var e = $("#data-table>tbody tr");
        e[0] && e.empty()
    }

    function initChangeValueType(e, t) {
        $("#valueType").val(e),
        t || (t = ""),
            $("#attrName").val(t),
            "attr" == e ? $(".ts-attrValue-div").css("display", "block") : $(".ts-attrValue-div").css("display", "none"),
        "html" != e && dealCheckBox("useHtml", !1)
    }

    function dealCheckBox(e, t) {
        t ? $("input[type='checkbox'][name='" + e + "']").prop("checked", !0) : $("input[type='checkbox'][name='" + e + "']").attr("checked", !1)
    }

    function initHtmlTags(e) {
        $("input[name='htmlEleGroup']:checkbox", $(".ts-htmlTag-items-div")).each(function () {
            $(this).prop("checked", !1)
        }),
        e && setCheckBoxGroup("htmlEleGroup", e.split(","))
    }

    function setFieldName(e, t) {
        $("input[name='fieldName']", t)[0].value = e
    }

    function focusInput(e) {
        $("input[name='fieldName']", $(e))[0].focus()
    }

    function runIfrFun(method, para1, para2, para3) {
        var ct = "CONTENT".toLowerCase();
        try {
            var cw = ct + win;
            if (eval('$("#ifr")[0].' + cw + "." + method)) {
                var func = eval('$("#ifr")[0].' + cw + "." + method);
                return func.call(func, para1, para2, para3)
            }
        } catch (e) {
        }
    }

    function clearIframe() {
        runIfrFun("clearAll")
    }

    function upSetConfigMap(e) {
        var t = getRowFieldId(e)
            , i = genFieldConfigObj(e);
        return allFieldConfigs[t] = i,
            i
    }

    function genFieldConfigObj(e) {
        var t = JSON.parse(JSON.stringify(fieldConfigObj))
            , i = getFieldName(e)
            , n = getRowFieldId(e);
        return t.id = n,
            t.name = i,
            t.selectors = "",
            t
    }

    function saveCurrFieldConfig() {
        currFieldConfig.selectors = getFieldPathValue(),
            allFieldConfigs[currFieldConfig.id] = currFieldConfig
    }

    function getFieldName(e) {
        return $("input[name='fieldName']", e)[0].value
    }

    function setFieldName(e, t) {
        $("input[name='fieldName']", t)[0].value = e
    }

    function getFieldPathValue() {
        return $("#xpathValue").val()
    }

    function setFieldPathValue(e) {
        return $("#xpathValue").val(e)
    }

    function clearFieldPathValue() {
        $("#xpathValue").val("")
    }

    function hlCurrTr(e) {
        $("#fields-table>tbody tr").removeClass(trHlClass),
            $(e).addClass(trHlClass)
    }

    function addRow() {
        var e = initTemplate("fields-table");
        return $("#fields-table>tbody tr:last").after(e),
            e
    }

    function initTemplate(e) {
        var t = $("#" + e + ">tbody>tr:first").clone(!0, !0);
        return resetTemplate(t),
            t
    }

    function resetTemplate(e) {
        e.removeAttr("style"),
            e.removeAttr("id"),
            $("input:text", e).val("");
        var t = "field-id-" + ++idOrder
            , i = "field_" + idOrder;
        $("input[name='rowFieldId']", e).val(t),
            $("input[name='fieldName']", e)[0].value = i,
            $("input[name='fieldName']", e).attr("value", i)
    }

    function getRowFieldId(e) {
        return $("input[name='rowFieldId']", e).val()
    }

    function saveXpath() {
        var e = $("#xpathValue").val();
        currFieldConfig.selectors,
            currFieldConfig.selectors = e,
            saveCurrFieldConfig()
    }

    function saveXpathAndLocation() {
        saveXpath(),
            initCurrTrShow()
    }

    function saveFileDown() {
        var e = getCheckRadio("fileSaveType");
        currFieldConfig.fileSaveType = e,
            saveCurrFieldConfig()
    }

    function initFileDown() {
        checkRadio("fileSaveType", currFieldConfig.fileSaveType),
            checkRadio("storageType", storageType),
            $("#httpPrefix").val(fileDownConfig.httpPrefix)
    }

    function saveFileStorage() {
        storageType = getCheckRadio("storageType"),
            fileDownConfig.httpPrefix = $("#httpPrefix").val(),
            saveCurrFieldConfig()
    }

    function saveDefaultValue() {
        currFieldConfig.defaultValue = $("#ts-defaultValue").val(),
            currFieldConfig.concatDelimiter = $("#concatDelimiter").val(),
            currFieldConfig.imgAttr = $("#imgAttr").val(),
            currFieldConfig.valueType = $("#valueType").val(),
            currFieldConfig.attrName = $("#attrName").val(),
            saveCurrFieldConfig(),
            $("#default-value-modal").modal("hide")
    }

    function saveModalDataAllLocal() {
        saveDataDealValue(),
            saveDefaultValue(),
            saveFileDown(),
            saveFileStorage(),
            saveReplaces(),
            saveDataDealAdv(),
            saveRegex(),
            saveXpath(),
            saveMutiPagrValue(),
            saveCurrFieldConfig(),
            resetFieldIconCurr(),
            initCurrTrShow()
    }

    function initCurrTrShow() {
        initTrShow(currentTr)
    }

    function initTrShow(e) {
        var t = getRowFieldId(e);
        initFieldConfigShow(allFieldConfigs[t]),
            resetValueAndPageSelector(),
            resetFieldIcon(e)
    }

    function saveDataDealValue() {
        currFieldConfig.delAllImg = getCheckRadio("delAllImg");
        var e = getCheckBox("delImgItem");
        currFieldConfig.delImg = e.join(","),
            currFieldConfig.dela = getCheckRadio("dela");
        var t = getCheckBox("delAsItem");
        currFieldConfig.delAs = t.join(",");
        var i = isCheckedById("pType") ? 1 : 0;
        currFieldConfig.pType = i;
        var n = isCheckedById("keepAlt") ? 1 : 0;
        currFieldConfig.keepAlt = n,
            currFieldConfig.preTxt = $("#preTxt").val(),
            currFieldConfig.tailTxt = $("#tailTxt").val(),
            currFieldConfig.randType = getCheckRadio("randType"),
            currFieldConfig.minRd = $("#minRd").val(),
            currFieldConfig.maxRd = $("#maxRd").val(),
            currFieldConfig.minRdtStr = $("#minRdtStr").val(),
            currFieldConfig.maxRdtStr = $("#maxRdtStr").val(),
            currFieldConfig.timeFmt = $("#timeFmt").val(),
            currFieldConfig.txtRd = $("#txtRd").val(),
            currFieldConfig.lenType = $("#lenType").val(),
            currFieldConfig.lenLimit = $("#lenLimit").val(),
            currFieldConfig.filterType = getCheckRadio("filterType"),
            currFieldConfig.noInclude = $("#noInclude").val(),
            currFieldConfig.mustInclude = $("#mustInclude").val()
    }

    function getCheckRadio(e, t) {
        return t ? $("input[type='radio'][name='" + e + "']:checked", t).val() : $("input[type='radio'][name='" + e + "']:checked").val()
    }

    function getCheckBox(e, t) {
        var i = []
            , n = [];
        return n = t ? $("input[type='checkbox'][name='" + e + "']:checked", t) : $("input[type='checkbox'][name='" + e + "']:checked"),
            $.each(n, function () {
                i.push($(this).val())
            }),
            i
    }

    function copyRow() {
        if (currentTr) {
            var e = jsonClone(currFieldConfig)
                , t = addRow()
                , i = getRowFieldId(t);
            setFieldConfigObjCommon(t, e),
                allFieldConfigs[i] = e
        } else
            alert("请选择要复制的字段，鼠标点一下字段名输入框即可")
    }

    function jsonClone(e) {
        return JSON.parse(JSON.stringify(e))
    }

    function setFieldConfigObjCommon(e, t) {
        var i = getFieldName(e)
            , n = getRowFieldId(e);
        return t.id = n,
            t.name = i,
            t
    }

    /**
     * 弹窗
     */
    function showMsgErr(e, t) {
        showMsg(e, "error", t)
    }

    function showMsgSuc(e, t) {
        showMsg(e, "success", t)
    }

    function showSaveSuc() {
        showMsgSuc("保存成功！")
    }

    function showMsg(e, t, i) {
        t=="success"?alertMsg(true,e):alertMsg(false,e);
        i && $("#" + i).focus();
    }

    function alertMsg(isSuccess, msg) {
        if (isSuccess) {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.open({
                    title: '成功'
                    , content: msg
                });
            });
        }else{
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.open({
                    title: '错误'
                    , content: msg
                });
            });
        }
    }

    function showMsgConfirm(e,f) {
        layer.open({
            content:e,
            custom:f,
            yes:function (index) {
                f(e)
                layer.close(index)
            }
        });
    }
})